package com.atguigu.yygh.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.hosp.client.HospitalFeignClient;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.orders.mapper.OrderInfoMapper;
import com.atguigu.yygh.orders.service.OrderInfoService;

import com.atguigu.yygh.orders.utils.HttpRequestHelper;
import com.atguigu.yygh.rabbit.RabbitService;
import com.atguigu.yygh.rabbit.constant.MqConst;
import com.atguigu.yygh.user.client.PatientFeignClient;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderCountQueryVo;
import com.atguigu.yygh.vo.order.OrderCountVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.lang.Assert;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-11-04
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private PatientFeignClient patientFeignClient;

    @Autowired
    private HospitalFeignClient hospitalFeignClient;

    @Autowired
    private RabbitService rabbitService;
    @Autowired
    OrderInfoMapper orderInfoMapper;


    @Override
    public long generateOrder(String scheduleId, Long patientId) {
        System.out.println("------------生成订单Service----------");
        // 根据患者id查询患者信息
        Patient patient = patientFeignClient.getPatientInfoById(patientId);
        // 根据排班id查询排班信息
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVoByScheduleId(scheduleId);


        // 封装远程调用医院接口所需的参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",scheduleOrderVo.getHoscode());
        paramMap.put("depcode",scheduleOrderVo.getDepcode());
        paramMap.put("hosScheduleId",scheduleOrderVo.getHosScheduleId());
        paramMap.put("reserveDate",new DateTime(scheduleOrderVo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", scheduleOrderVo.getReserveTime());
        paramMap.put("amount",scheduleOrderVo.getAmount()); //挂号费用
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        //String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", "");
        // 发送远程http请求医院模拟系统------------------------------------
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/submitOrder");

        if (result.getInteger("code") != 200) { // 先判断，只要不是200都挂号失败
            throw new YyghException(20001,"挂号失败");
        }
        // 得到医院返回的数据
        JSONObject jsonObject = result.getJSONObject("data");

        // 存储到数据库order_info表中--------------------------------
        OrderInfo orderInfo = new OrderInfo();
        String hosRecordId = jsonObject.getString("hosRecordId"); //预约记录唯一标识（医院预约记录主键）
        Integer number = jsonObject.getInteger("number");  // 预约序号
        String fetchTime = jsonObject.getString("fetchTime");  //取号时间
        String fetchAddress = jsonObject.getString("fetchAddress");; //取号地址
        String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100); // 订单号
        //设置添加数据--排班数据
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
        //设置添加数据--就诊人数据
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        //设置添加数据--医院接口返回数据
        orderInfo.setHosRecordId(hosRecordId);
        orderInfo.setNumber(number);
        orderInfo.setFetchTime(fetchTime);
        orderInfo.setFetchAddress(fetchAddress);

        //调用方法添加------------
        baseMapper.insert(orderInfo);


        //1  异步操作：调用方法发送消息消息队列，更新mongodb的排班可用挂号数availableNumber，不用-1
        Integer availableNumber = jsonObject.getInteger("availableNumber");
        Integer reservedNumber = jsonObject.getInteger("reservedNumber");
        OrderMqVo orderMqVo = new OrderMqVo();
        orderMqVo.setAvailableNumber(availableNumber);
        orderMqVo.setReservedNumber(reservedNumber);
        orderMqVo.setScheduleId(scheduleId);  // mongodb的排班objectId唯一，有这个才能修改数据

        // 2 异步操作：发送挂号成功的短信提示到消息队列
        MsmVo msmVo = new MsmVo();
        Map<String,Object> params = new HashMap<>(){{
            put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
            put("amount", orderInfo.getAmount());
            put("reserveDate", new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")+ (orderInfo.getReserveTime()==0?"上午":"下午"));
            put("name", orderInfo.getPatientName());
            put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
        }};
        msmVo.setPhone(patient.getPhone());
        msmVo.setParam(params);

        orderMqVo.setMsmVo(msmVo);

        // 发送
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);

        // 返回订单的id,插入orderInfo表后，mybatis会回写主键id
        return orderInfo.getId();  // 订单id
    }

    @Override
    public OrderInfo getOrderById(Long orderId) {
        OrderInfo orderInfo = this.getById(orderId);
        OrderInfo orderInfoPacked = this.packOrderInfo(orderInfo);
        return orderInfoPacked;
    }

    @Override
    public boolean cancelOrder(Long orderId) {
        OrderInfo orderInfo = this.getOrderById(orderId);
        // 先判断时间是否满足能取消
        Assert.isTrue(new DateTime(orderInfo.getQuitTime()).isAfterNow(),"已超过取消截止时间");
        // 判断这条订单的状态是不是-1 ,是-1就不在更新，直接返回提示已经更新过
        Assert.isTrue(orderInfo.getOrderStatus() != OrderStatusEnum.CANCLE.getStatus().intValue(),"已经取消过了，请不要重复取消");

        // 远程调用医院接口
        // 封装所需参数
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        reqMap.put("sign", "");
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, "http://localhost:9998/order/updateCancelStatus");
        // 这个接口不返回date，只需判断code状态，决定下面操作
        Assert.isTrue(result.getInteger("code") == 200,"取消预约失败，远程调用医院系统失败");


        // 更新mysql orderInfo表的order_status为-1
        LambdaUpdateWrapper<OrderInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<OrderInfo>();
        lambdaUpdateWrapper.eq(OrderInfo::getId,orderId);
        lambdaUpdateWrapper.set(OrderInfo::getOrderStatus,OrderStatusEnum.CANCLE.getStatus());
        this.update(lambdaUpdateWrapper);

        // 发mq，hosp服务监听，更新mongodb 的availableNumber +1
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER_CANSEL,MqConst.ROUTING_ORDER_CANSEL,orderInfo.getScheduleId());

        // 发送mq，让sms发送短信给用户
        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,msmVo);

        return true;
    }

    //条件：医院名称，时间范围
    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {

        List<OrderCountVo> orderCountVoList =  orderInfoMapper.selectCountMap(orderCountQueryVo);
        //日期列表
        List<String> reserveDateList = orderCountVoList.stream().map(((orderCountVo) -> {
            return orderCountVo.getReserveDate();
        })).toList();
        //统计数量列表
        List<Integer> countList = orderCountVoList.stream().map((orderCountVo) -> {
            return orderCountVo.getCount();
        }).toList();

        Map<String,Object> map = new HashMap<>();
        map.put("dateList",reserveDateList);
        map.put("countList",countList);

        

        return map;
    }

    private OrderInfo packOrderInfo(OrderInfo orderInfo){
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));

        return orderInfo;
    }
}
